package com.tjbank.cssys.service.impl;

import com.tjbank.cssys.api.SequenceService;
import com.tjbank.cssys.mybatis.IamSequenceDao;
import com.tjbank.cssys.mybatis.entity.IamSequence;
import com.tjbank.cssys.mybatis.sqlbuilder.IamSequenceSqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 自定义组织树编号生成器
 * 
 * Package : com.tansun.magicube.iam.service.impl
 * 
 * @author -- lijiangtao 2020年5月6日 下午7:54:14
 *
 */
@Service
public class SequenceServiceImpl implements SequenceService {

    @Autowired
    private IamSequenceDao sequenceDao;

    /**
     * 根据编码前缀获取新编码
     * 
     * @param prefix
     * @return
     * @author -- lijiangtao 2020年5月7日 下午7:54:35
     */
    @Override
    @Transactional
    public String getNextVal(String prefix) {
        IamSequenceSqlBuilder sqlBuilder = new IamSequenceSqlBuilder();
        sqlBuilder.andPrefixEqualTo(prefix);
        IamSequence entity = sequenceDao.selectBySqlBuilder(sqlBuilder);
        if (entity == null) {
            entity = new IamSequence();
            entity.setCurrval(0);
            entity.setIncrement(1);
            entity.setPrefix(prefix);
            sequenceDao.insert(entity);
        }
        entity.setCurrval(entity.getCurrval() + entity.getIncrement());
        sequenceDao.updateBySqlBuilder(entity, sqlBuilder);
        int currval = entity.getCurrval();
        int length = String.valueOf(currval).length();
        int capacity = entity.getDigitcapacity();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < capacity - length; i++) {
            result.append("0");
        }
        return result.append(currval).toString();
    }
}
